package view;

import dao.Blog;
import dao.BlogDao;
import dao.User;
import session.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/delete")
public class Delete extends HttpServlet {
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        User user = Session.isLogin(req);
        if (user == null){
            //resp.sendRedirect("login.html");
            resp.setStatus(403);
            String html = "<h3> 请先登录 </h3>";
            resp.getWriter().write(html);
            return;
        }
        String blogId = req.getParameter("blogId");
        if (blogId == null){
            resp.setStatus(403);
            String html = "<h3> 博客不存在 </h3>";
            resp.getWriter().write(html);
            return;
        }
        BlogDao blogDao = new BlogDao();
        try {
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blog == null){
                resp.setStatus(403);
                String html = "<h3> 博客不存在 </h3>";
                resp.getWriter().write(html);
                return;
            }
            if (blog.getUserId() != user.getUserId()){
                resp.setStatus(403);
                String html = "<h3> 小伙子你的想法很危险啊,不能删除别人的文章 </h3>";
                resp.getWriter().write(html);
                return;
            }
            blogDao.delete(blog.getBlogId());
            resp.setStatus(200);
            String html = "<h3> 删除成功 </h3>";
            resp.getWriter().write(html);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
